# all the imports
import sqlite3
from flask import Flask, request, session, g, redirect, url_for
from flask import abort, render_template, flash
from tsql import *
# configuration
DEBUG = True
SECRET_KEY = 'development key'

# create out little application
app = Flask(__name__)
app.config.from_object(__name__)


@app.route('/')
def home_page():
    return render_template('Todos.html')


def add_user(username, userpasswd):
    admin= usertable(
            name = username,
            passwd = userpasswd)

    qsession = get_session()
    qsession.add(admin)
    qsession.commit()

@app.route('/register', methods=['GET', 'POST'])
def register():
    error = None
    if request.method == 'POST':
        username = request.form['username']
        userpasswd = request.form['password']
        add_user(username, userpasswd)
        print 'register ok'
        flash('you were register')
        return redirect(url_for('home_page'))

    return render_template('register.html', error=error)

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        qsession = get_session()
        username = request.form['username']
        query = qsession.query(usertable).filter_by(name=username).first()

        if request.form['username'] != query.name:
            error = 'Invalid username'
        elif request.form['password'] != query.passwd:
            print query.passwd
            error = 'Invalid password'
        else:
            session['logged_in'] = True
            session['cur_username'] = request.form['username']
            session['cur_user_id'] = query.userid
            flash('you were logged in')
            print 'login ok'
        
            return redirect(url_for('home_page'))

    return render_template('login.html', error=error)


@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    flash('you were logged out')
    print 'logout ok'
    return redirect(url_for('home_page'))
    
if __name__ == '__main__':
    app.run()
